package com.xiang.api.service;

import java.io.File;
import java.io.PrintWriter;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import com.xiang.api.Util;

import org.springframework.stereotype.Service;

@Service
public class ReadFile {

  public void index(HttpServletRequest request, HttpServletResponse response) throws Exception {
    String str = "public" + request.getRequestURI();
    // response.setCharacterEncoding("utf-8");
    str = Util.formatFilename(str, false);
    String mime = Util.formatFilename("public", true);
    if (str.indexOf(mime) != 0) {
      throw new RuntimeException("路径非法");
    }
    response.setHeader("Content-type", Util.mime("txt"));
    File fi = new File(str);
    while (!fi.exists() || fi.isDirectory()) {
      str += "/index.html";
      try {
        fi = new File(str);
        if (!fi.exists()) {
          PrintWriter writer = response.getWriter();
          writer.write("别费劲了,没这玩意");
          writer.close();
          return;
        }
      } catch (Exception e) {
        // response.getOutputStream().write("哦豁~!你把我搞坏了".getBytes());
        PrintWriter writer = response.getWriter();
        writer.write("哦豁~!你把我搞坏了");
        writer.close();
        response.reset();
        return;
      }
    }

    byte[] d = Util.readFile(str);
    mime = Util.mime(str.substring(str.lastIndexOf(".") + 1));
    response.setHeader("content-type", mime);
    response.getOutputStream().write(d);

  }

}
